package com.zrkj.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.zrkj.entity.vo.Result;
import com.zrkj.exception.SystemErrorType;
import com.zrkj.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;


@Slf4j
public class UserInterceptor implements HandlerInterceptor {


    private final String[] whiteList = {"swagger", "v3","error","/login","/getUrl2","/test"};

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        String path = request.getRequestURI();
        for (String whiteName : whiteList) {
            if (StrUtil.contains(path, whiteName)) {
                return true;
            }
        }


        String token = request.getHeader("token");
        if (checkToken(token)) {
            Map<String, String> tokenMap = new HashMap<>(1);
            String userId = JwtUtil.getUserId(token);
            tokenMap.put("userId", userId);
            String userName = JwtUtil.getUserName(token);
            tokenMap.put("userName",userName);
            UserContextHolder.getInstance().setContext(tokenMap);
            return true;
        } else {
            response.getWriter().println(JSONUtil.toJsonStr(Result.fail(SystemErrorType.TOKEN_INVALID)));
            response.flushBuffer();
            return false;

        }
//return true;

    }

    /**
     * 校验token
     *
     * @param token
     */
    private Boolean checkToken(String token) {

        if (StrUtil.isNotBlank(token) && JwtUtil.verify(token)) {

            return true;
        }

        return false;
    }

    @Override
    public void afterCompletion(
            HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {

        UserContextHolder.getInstance().clear();
    }
}
